import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:message_tools/components/appbar_plugins.dart';
import 'package:message_tools/model/basebean.dart';
import 'package:message_tools/ui/page/sms/sms_home_page.dart';
import 'package:message_tools/utils/platform_utils.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:toast/toast.dart';

class HomePage extends StatelessWidget {
  int _serviceVersionCode;
  String _downloadURL = "";
  String _updaterContent = "";
  bool _isShowDialog = false;
  BuildContext _context;

  HomePage() {
    /*Future.delayed(Duration(seconds: 10)).then((_) {
      debugPrint("xxxxxxx");
      if (!_isShowDialog) {
        debugPrint("_getNewVersionAPP");
        _getNewVersionAPP(_context);
      }
    });*/
  }

  Widget build(BuildContext context) {
    if (!_isShowDialog) {
      _getNewVersionAPP(context);
    }

    var list = BaseBean.getBaseBeans();
    List<Widget> lists = [];
    for (var item in list) {
      var border = new Border(
        right: new BorderSide(
            width: 0.8, style: BorderStyle.solid, color: Colors.grey),
        bottom: new BorderSide(
            width: 0.8, style: BorderStyle.solid, color: Colors.grey),
      );

      lists.add(new Container(
          height: 40.0,
          width: 40.0,
          decoration: new BoxDecoration(
            //背景
            color: Colors.white,
            //设置四周边框
            border: border,
          ),
          child: new Center(
              child: GestureDetector(
            onTap: () {
              if (item.title == "短信") {
                Navigator.push(
                  context,
                  new MaterialPageRoute(
                      builder: (context) => new SmsHomePage()),
                );
              } else {
                showToast("即将上线，敬请期待", context);
              }
            }, //写入方法名称就可以了，但是是无参的
            child: new Column(
                //平分空白
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    width: 60,
                    height: 60,
                    child: Image.asset('assets/images/' + item.image),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 5),
                    child: new Text(item.title, style: TextStyle(fontSize: 18)),
                  ),
                ]),
          ))));
    }

    var gridview = GridView.count(
      //一行多少个
      crossAxisCount: 3,
      //滚动方向
      scrollDirection: Axis.vertical,

      //宽高比
      childAspectRatio: 2 / 2,

      //设置itemView
      children: lists,
    );

    return MaterialApp(
      home: Scaffold(appBar: AppBarPlugin.Create("小强群发助手"), body: gridview),
    );
  }

  void showToast(String msg, BuildContext context,
      {int duration, int gravity}) {
    Toast.show(msg, context, duration: duration, gravity: gravity);
  }

  _getNewVersionAPP(BuildContext context) async {
    _isShowDialog = true;
    var appVersion = await PlatformUtils.getAppVersion();

    String url = "http://47.102.217.170/v1/open/get_version";
    Dio().get(url).then((response) {
      if (response != null) {
        var data = response.data["data"];
        debugPrint("data01: $data \n");
        debugPrint("data02: ${data["version"]} \n");
        var version = data["version"];
        if (appVersion != version) {
          _downloadURL = data["app_url"].toString();
          var updaterContent = data["content"] ?? "";
          var contents = updaterContent.split("\\n");
          contents.forEach((content) {
            _updaterContent = "$_updaterContent$content\n";
          });

          mAlertDialog(context, _updaterContent);
        }
      }
    });
  }

  void mAlertDialog(BuildContext context, String content) {
    showDialog(
      context: context,
      barrierDismissible: true, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('系统提示'),
          content: Text(content),
          actions: <Widget>[
            FlatButton(
              child: Text('确定'),
              onPressed: () {
                downloadApp(context, _downloadURL);
                Navigator.of(context).pop();
              },
            ),
          ],
          elevation: 20,
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        );
      },
    );
  }

  Future downloadApp(BuildContext context, String url) async {
    var externalDirectory = await getExternalStorageDirectory();
    String apkPath = externalDirectory.path + '/' + url.split('/').last;
    debugPrint("apkPath = $apkPath \n");

    File file = File(apkPath);
    if (file.existsSync()) {
      file.deleteSync();
    }

    await showDownloadDialog(context, url, apkPath);
    OpenFile.open(apkPath);

    /*File file = File(apkPath);
    if (!file.existsSync()) {
      // 没有下载过
      await showDownloadDialog(context, url, apkPath);
      OpenFile.open(apkPath);
    } else {
      var reDownload = await showReDownloadDialog(context);
      //因为点击android的返回键,关闭dialog时的返回值为null
      if (reDownload != null) {
        if (reDownload) {
          await showDownloadDialog(context, url, apkPath);
        }
        OpenFile.open(apkPath);
      }
    }*/
    _isShowDialog = false;
  }

  showDownloadDialog(context, url, path) async {
    /// TODO ProgressDialog目前无法监听dialog的关闭事件,导致无法配合cancel下载的操作
    /// 需要重新实现
    ProgressDialog dialog = ProgressDialog(context,
        type: ProgressDialogType.Download, isDismissible: !inProduction);
    dialog.show();
    await Dio().download(url, path, onReceiveProgress: (progress, total) {
      if (total != -1) {
        dialog.update(
            progress: double.parse((progress / total * 100).toStringAsFixed(2)),
            maxProgress: 100,
            message: "下载中");
      }
    });
    dialog.dismiss();
  }

  showReDownloadDialog(context) async {
    return await showDialog(
        context: context,
        builder: (context) => AlertDialog(
              content: Text(_updaterContent),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text(
                    "取消",
                    style: TextStyle(color: Colors.black.withOpacity(0.5)),
                  ),
                ),
                SizedBox(
                  width: 20,
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                  child: Text(
                    "重新下载",
                    style: TextStyle(color: Colors.black),
                  ),
                ),
                FlatButton(
                  onPressed: () async {
                    Navigator.of(context).pop(false);
                  },
                  child: Text("安装APP"),
                ),
              ],
            ));
  }
}
